package com.ttxz.common.base.model

import com.ttxz.common.BuildConfig
import com.ttxz.common.http.*

/**
 * 简要说明
 *
 * @author ttxz
 * @date 2022/6/11 12:46
 */
abstract class BaseModel {
    suspend fun <T> executeHttp(block:suspend() -> HttpResponse<T>):HttpResponse<T>{
        kotlin.runCatching {
            block.invoke()
        }.onSuccess { data:HttpResponse<T> ->
            return handleHttpOk(data)
        }.onFailure {e ->
            return handleHttpError(e)
        }
        return HttpEmptyResponse()
    }
    /**
     * 非后台返回错误，捕获到的异常
     */
    private fun <T> handleHttpError(e: Throwable): HttpResponse<T> {
        if (BuildConfig.DEBUG) e.printStackTrace()
//        handlingExceptions(e)
        return HttpErrorResponse(e)
    }

    /**
     * 返回200，但是还要判断isSuccess
     */
    private fun <T> handleHttpOk(data: HttpResponse<T>): HttpResponse<T> {
        return if (data.isSuccess) {
            getHttpSuccessResponse(data)
        } else {
//            handlingApiExceptions(data.errorCode, data.errorMsg)
            HttpDataFailedResponse(data.errorCode, data.errorMsg)
        }
    }

    /**
     * 成功和数据为空的处理
     */
    private fun <T> getHttpSuccessResponse(response: HttpResponse<T>): HttpResponse<T> {
        return if (response.data == null || response.data is List<*> && (response.data as List<*>).isEmpty()) {
            HttpEmptyResponse()
        } else {
            HttpSuccessResponse(response.data!!)
        }
    }
}